/*
 * @Author: zy
 * @Date: 2022-06-07 19:14:18
 * @LastEditTime: 2022-07-26 21:36:09
 * @Description: 登录Token
 */
import { localStorageKey } from "@/config";
import memberApis from "@/services/apis/member";
import { toast } from "@/utils";
import wxApis from "@/services/apis/wx";
import { devMode } from "@/config";

const hasLoginHandler = async ({ state, dispatch }) => {
  // 加载用户信息
  if (!state.userInfo) {
    memberApis.getMemberInfo(false, false, false);
  }
};

const saveToken = async ({ state, dispatch }, params) => {
  //console.log("saveToken:", params);
  let nowDateTime = new Date().getTime();
  //jbolt token默认2小时过期
  let expireTime = 60 * 60 * 2 * 1000;
  console.log(
    "token失效时间:",
    uni.$u.timeFormat(
      new Date(nowDateTime + expireTime),
      "yyyy年mm月dd日 hh时MM分ss秒"
    )
  );
  uni.setStorageSync(localStorageKey.token, params.token);
  uni.setStorageSync(localStorageKey.tokenExpireTime, nowDateTime + expireTime);
  if (params.refreshToken) {
    //jbolt refreshToken默认7天过期
    let refreshExpireTime = 60 * 60 * 24 * 7 * 1000;
    console.log(
      "refreshToken失效时间:",
      uni.$u.timeFormat(
        new Date(nowDateTime + refreshExpireTime),
        "yyyy年mm月dd日 hh时MM分ss秒"
      )
    );
    uni.setStorageSync(localStorageKey.refreshToken, params.refreshToken);
    uni.setStorageSync(
      localStorageKey.refreshTokenExpireTime,
      nowDateTime + refreshExpireTime
    );
  } else {
    dispatch("removeRefreshToken");
  }
  // 已登录处理
  await hasLoginHandler({ state, dispatch });
  state.hasLogin = true;
};

const checkRefreshToken = () => {
  let refreshToken = uni.getStorageSync(localStorageKey.refreshToken);
  let refreshTokenExpireTime = uni.getStorageSync(
    localStorageKey.refreshTokenExpireTime
  );
  if (refreshToken) {
    let nowDateTime = new Date().getTime();
    if (nowDateTime < refreshTokenExpireTime) {
      return true;
    }
  }
  return false;
};

const checkToken = () => {
  let token = uni.getStorageSync(localStorageKey.token);
  let expireTime = uni.getStorageSync(localStorageKey.tokenExpireTime);
  if (token) {
    let nowDateTime = new Date().getTime();
    if (nowDateTime < expireTime) {
      return true;
    }
  }
  return false;
};

export default {
  state: {
    hasLogin: false,
    userInfo: null
  },
  actions: {
    toLogin({ state, dispatch }) {
      console.log("toLogin-调用了检测登录");
      return new Promise(async resolve => {
        // #ifdef H5
        console.log("h5平台");
        if (devMode) {
          console.log("开发模式 手动复制微信token数据，即可完成自动登录");
          if (checkToken()) {
            // 已登录处理
            await hasLoginHandler({
              state,
              dispatch
            });
            state.hasLogin = true;
            resolve(true);
          }
        }
        // #endif
        // #ifdef MP-WEIXIN
        dispatch("wxLogin")
          .then(
            async loginRes => {
              //console.log("token.js toLogin", loginRes);
              if (loginRes.token) {
                await saveToken({ state, dispatch }, loginRes);
                resolve(true);
              } else {
                state.hasLogin = false;
                resolve(false);
              }
            },
            err => {
              console.log("登录失败", err);
            }
          )
          .catch(err => {
            console.log("登录异常", err);
          });
        // #endif
      });
    },
    async setToken({ state, dispatch }, info) {
      await saveToken({ state, dispatch }, info);
      return true;
    },
    logout({ state, dispatch }) {
      dispatch("removeToken");
      dispatch("removeRefreshToken");
      dispatch("removeUserInfo");
      dispatch("removeSessionKey");
    },
    removeToken({ state }) {
      uni.removeStorageSync(localStorageKey.token);
      uni.removeStorageSync(localStorageKey.tokenExpireTime);
    },
    removeRefreshToken({ state }) {
      uni.removeStorageSync(localStorageKey.refreshToken);
      uni.removeStorageSync(localStorageKey.refreshTokenExpireTime);
    },
    removeUserInfo({ state }) {
      uni.removeStorageSync(localStorageKey.memberId);
      state.userInfo = null;
      state.hasLogin = false;
    },
    setUserSaveInfo({ state }, info) {
      if (info.id) {
        uni.setStorageSync(localStorageKey.memberId, info.id);
      }
      state.userInfo = info;
    },
    getUserInfo({ state }, loading = false) {
      return new Promise(async resolve => {
        if (state.userInfo && !loading) {
          resolve(state.userInfo);
        } else {
          let info = await memberApis.getMemberInfo();
          resolve(info);
        }
      });
    },
    getHasLogin({ state }) {
      return state.hasLogin;
    },
    toRegisterByPhone({ state, dispatch }, params) {
      return new Promise(resolve => {
        uni.showLoading({
          title: "请稍等",
          mask: true
        });
        wxApis.registerByPhone(params).then(
          registerRes => {
            console.log("注册返回:", registerRes);
            dispatch("setToken", registerRes).then(() => {
              toast("登录成功");
              resolve(state.userInfo);
            });
          },
          err => {
            resolve(false);
            toast(err.msg ? err.msg : "注册失败，请稍后再试");
          }
        );
      });
    },
    refreshJwtToken({ state, dispatch }) {
      if (checkToken() == false && checkRefreshToken() == true) {
        //刷新token
        return new Promise(resolve => {
          wxApis.wxRefreshToken().then(
            async refresh => {
              console.log("token.js refreshToken");
              if (refresh.token) {
                  await saveToken({ state, dispatch }, refresh);
                  resolve(true);
                } else {
                  resolve(false);
                }
            },
            err => {
              resolve(false);
              toast("checkRefreshToken失败");
            }
          );
        });
      } else {
        //重新登录获取token
        return new Promise(resolve => {
          dispatch("wxLogin")
            .then(
              async loginRes => {
                console.log("token.js wxLogin token");
                if (loginRes.token) {
                  await saveToken({ state, dispatch }, loginRes);
                  resolve(true);
                } else {
                  state.hasLogin = false;
                  resolve(false);
                }
              },
              err => {
                console.log("登录失败", err);
              }
            )
            .catch(err => {
              console.log("登录异常", err);
            });
        });
      }
    }
  },
  getters: {
    hasLogin: state => state.hasLogin,
    userInfo: state => state.userInfo
  }
};
